package com.hythzx.service.mapper;

import com.hythzx.config.utils.Constants;
import com.hythzx.domain.Authority;
import com.hythzx.domain.Role;
import com.hythzx.domain.User;
import com.hythzx.service.dto.UserDTO;
import org.mapstruct.MapMapping;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * Created by hythzx on 2017/3/4.
 */
@Mapper(componentModel = "spring")
public interface UserMapper {

    @Mapping(source = "userName",target = "name")
    @Mapping(source = "loginName",target = "username")
    @Mapping(source = "roles",target = "authorities")
    @Mapping(source = "active",target = "enabled")
    UserDTO userToUserDTO(User user);

    default boolean enableFromString(String active){
        if(active == null){
            return false;
        }
        if(active.trim().equals(Constants.TRUE)){
            return true;
        }else{
            return false;
        }
    }

    default Set<GrantedAuthority> GrantedAuthorityFromRoles(Set<Role> roles){
        if(roles == null){
            return null;
        }
        Set<GrantedAuthority> grantedAuthorities = new CopyOnWriteArraySet<>();
        GrantedAuthority grantedAuthority;
        for (Role role : roles) {
            Set<Authority> authorities = role.getAuthorities();
            if (authorities != null){
                for (Authority authority : authorities) {
                    grantedAuthority = new SimpleGrantedAuthority(authority.getPermission());
                    grantedAuthorities.add(grantedAuthority);
                }
            }
        }
        return grantedAuthorities;
    }
}
